<?php

namespace addons\kuerp\controller;

use addons\kuerp\model\Admin;
use addons\kuerp\model\GoodsSales;
use addons\kuerp\model\StaffSignIn;
use addons\kuerp\model\StaffMember;
use addons\kuerp\model\Collection;
use app\admin\model\department\Admin as AdminDepartment;
use addons\kuerp\model\Achievement;
use addons\kuerp\model\Event;
use addons\kuerp\model\Feedback;
use addons\kuerp\model\PartsStockReload;
use addons\kuerp\model\Customers;
use addons\kuerp\model\Contacts;
use addons\kuerp\model\Contract;
use addons\kuerp\model\Leads;
use addons\kuerp\model\Receivables;
use addons\kuerp\model\Staff;
use addons\kuerp\model\Business;
use addons\kuerp\model\Parts;
use addons\kuerp\model\Approval;
use addons\kuerp\model\Consume;
use addons\kuerp\model\Quote;
use addons\kuerp\model\Record;
use addons\kuerp\model\ExamineRecord;
use addons\kuerp\model\ReceivablesPlan;
use think\Db;
use think\Exception;

/**
 * 首页接口
 */
class Index extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        try{
            \think\Db::execute("SET @@sql_mode='';");
        }catch (Exception $e){

        }
    }

    //数据简报
    public function briefing()
    {
        $times = input('times');//2021-01,2021-07
        $type = input('type', 2);//2下属 1本人 0团队
        if (empty($times)) {
            $this->error('筛选时间不能为空');
        }
        $sale_users = $this->auth->sale_users ?? [];
        $adminids = $this->auth->adminids ?? [];
         
        $whereStaff2=[];
        if ($type == 1) {//我的
            $whereStaff2['staff_id'] = $this->auth->staff_member_id;
        } elseif ($type == 2) {//下属
            //本人存在 则剔除自己
            if (in_array($this->auth->staff_member_id, $sale_users)) {
                $sale_users = array_diff($sale_users, [$this->auth->staff_member_id]);
            }
            $whereStaff2['staff_id'] = ['in', $sale_users];
        } else {
            $whereStaff2['staff_id'] = ['in', $sale_users];
        }
        
        $times = setTimes($times, 'time');
        // $startTime = strtotime($times[0]);
        // $endTime = strtotime($times[1]);

        $where = ['createtime' => ['between', $times]];

        //拜访次数
        $baifang = StaffSignIn::where($where)->where($whereStaff2)->count();

        $where = [
            'createtime' => ['between', $times]
        ];
        $whereC = [
            'purchase_time' => ['between', $times]
        ];
        $whereR = [
            'purchase_time' => ['between', $times]
        ];
        $whereRc = [
            'createtime' => ['between', $times]
        ];
        if ($type == 1) {
            $where['staff_member_id'] = $this->auth->staff_member_id;
            $whereC['sale_user'] = $this->auth->staff_member_id;
            $whereR['staff_member_id'] = $this->auth->staff_member_id;
            $whereRc['admin_id'] = $this->auth->id;
        } elseif ($type == 2) {
            $where['staff_member_id'] = ['in', $sale_users];
            $whereC['sale_user'] = ['in', $sale_users];
            $whereR['staff_member_id'] = ['in', $sale_users];
            //本人存在 则剔除自己
            if (in_array($this->auth->id, $adminids)) {
                $adminids = array_diff($adminids, [$this->auth->id]);
            }
            $whereRc['admin_id'] = ['in', $adminids];
        } else {
            $where['staff_member_id'] = ['in', $sale_users];
            $whereC['sale_user'] = ['in', $sale_users];
            $whereR['staff_member_id'] = ['in', $sale_users];
            $whereRc['admin_id'] = ['in', $adminids];
        }
        //报价次数
        $quote = 0;//Quote::where($where)->count();
        //客户 线索 联系人 合同 回款 跟进次数 处理审批
        $leads = 0;//Leads::where($where)->count();
        $customer = Customers::where($where)->count();
        $contacts = 0;//Contacts::where($where)->count();
        $contract = GoodsSales::where($whereC)->count();
        $contract_money = GoodsSales::where($whereC)->sum('real_money+back_money');
        $receivables_money = Collection::where(['examine_status' => 1])->where($whereR)->sum('money');
        $record = Record::where($whereRc)->where(['follow_type' => ['neq', '其它']])->count();

        //商机总数
        $business = 0;//Business::where($where)->count();
        //客户成交量
        $customer_complate = 0;//Customers::where($where)->where(['contract_status' => 1])->count();
        //客户未成交量
        $customer_nocomplate = 0;//Customers::where($where)->where(['contract_status' => 0])->count();
        //商机成交总数
        $business_complate =0;// Business::where($where)->where(['contract_status' => 1])->count();
        //商机未成交总数
        $business_nocomplate = 0;//Business::where($where)->where(['contract_status' => 0])->count();
        //商机成交金额
        $business_complate_money = 0;//Business::where($where)->where(['contract_status' => 1])->sum('money');
        //商机未成交金额
        $business_nocomplate_money = 0;//Business::where($where)->where(['contract_status' => 0])->sum('money');

        $this->success('请求成功', [
            'baifang' => $baifang,
            'quote' => $quote,
            'leads' => $leads,
            'customer' => $customer,
            'contacts' => $contacts,
            'contract' => $contract,
            'contract_money' => round($contract_money, 2),
            'receivables' => round($receivables_money, 2),
            'record' => $record,
            'business' => $business,
            'customer_complate' => $customer_complate,
            'customer_nocomplate' => $customer_nocomplate,
            'business_complate' => $business_complate,
            'business_nocomplate' => $business_nocomplate,
            'business_complate_money' => $business_complate_money,
            'business_nocomplate_money' => $business_nocomplate_money,]);
    }




    //首页目标完成情况
    public function getAchievement()
    {
        $times = input('times');//2021-01,2021-07
        $team_type = input('team_type', 3);//3我的 2我的团队
        if (empty($times)) {
            $this->error('筛选时间不能为空');
        }
        $times = setTimes($times, 'datetime');

        //业绩目标
        $contractAchievement = 0;//Achievement::getStaffTeamAchievement($times[0], $times[1], $this->auth, Achievement::CONTRACT_TYPE, $team_type) ?? 0;
        //获客目标
        $customerAchievement = 0;//Achievement::getStaffTeamAchievement($times[0], $times[1], $this->auth, Achievement::CUSTOMER_TYPE, $team_type) ?? 0;
        //拜访目标
        $visitAchievement = 0;//Achievement::getStaffTeamAchievement($times[0], $times[1], $this->auth, Achievement::VISIT_TYPE, $team_type) ?? 0;

        $startTime = strtotime($times[0] . '-1');
        $endTime = strtotime(date('Y-m-t', strtotime($times[1]))) + 86400 - 1;
        //转为职员id
        $sale_users = $this->auth->sale_users ?? [];
        if ($team_type == 3) {//我的
            $showStaffIds = [$this->auth->staff_member_id];
        } elseif ($team_type == 2) {//团队
            $showStaffIds = $sale_users;
        } else {
            $this->error('参数错误');
        }

        //业绩
        $contractCount = GoodsSales::where(['examine_status' => 1, 'sale_user' => ['in', $showStaffIds], 'purchase_time' => ['between', [$startTime, $endTime]]])->sum('real_money+back_money');
        //获客
        $customerCount = Customers::where(['createtime' => ['between',[$startTime, $endTime]], 'staff_member_id' => ['in', $showStaffIds]])->count();
        //拜访
        // $visitCount = Event::where(['type' => 1, 'status' => 2, 'actual_end_time' => ['between', [$startTime, $endTime]],
        //     'staff_id' => ['in', $showStaffIds]])->count();
        //拜访
        $visitCount = Record::where(['createtime' => ['between', [$startTime, $endTime]],
            'admin_id' => ['in', $this->auth->adminids]])->count();
        $this->success('请求成功', [
            'contract' => [
                'achievement' => $contractAchievement,
                'count' => $contractCount,
                'ratio' => getRatio($contractCount, $contractAchievement)
            ],
            'customer' => [
                'achievement' => $customerAchievement,
                'count' => $customerCount,
                'ratio' => getRatio($customerCount, $customerAchievement)
            ],
            'event' => [
                'achievement' => $visitAchievement,
                'count' => $visitCount,
                'ratio' => getRatio($visitCount, $visitAchievement)
            ],
        ]);
    }

    //财务简报
    public function financeBriefing()
    {
        $todayStart = strtotime(date('Y-m-d'));
        $todayEnd = strtotime(date('Y-m-d')) + 86400 - 1;

        $approval = Approval::where(['createtime' => ['between', [$todayStart, $todayEnd]]])->where('', 'exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',flow_staff_id)'))->count();
        $consume = Consume::where(['createtime' => ['between', [$todayStart, $todayEnd]]])->where('', 'exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',flow_staff_id)'))->count();
        $receivables = Receivables::where(['createtime' => ['between', [$todayStart, $todayEnd]]])->where('', 'exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',flow_staff_id)'))->count();
        $contract = Contract::where(['createtime' => ['between', [$todayStart, $todayEnd]]])->where('', 'exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',flow_staff_id)'))->count();


        $this->success('请求成功', [
            'approval' => $approval,
            'consume' => $consume,
            'receivables' => $receivables,
            'contract' => $contract
        ]);
    }

    //报价单
    public function quote()
    {
        $where = function ($query) {
            $query->where('create_staff_id|owner_staff_id', 'in', Staff::getMyStaffIds())
                ->whereOr('', 'exp', "FIND_IN_SET({$this->auth->id},show_staff_id)");
        };
        $daishenhe = Quote::where([ 'check_status' => ['in', [0, 1]]])
            ->where($where)->count();
        $shenhetongguo = Quote::where([ 'check_status' => 2])
            ->where($where)->count();
        $shenhejujue = Quote::where([ 'check_status' => 3])
            ->where($where)->count();
        $zuofei = Quote::where([ 'check_status' => 4])
            ->count();

        $this->success('请求成功', ['daishenhe' => $daishenhe, 'shenhetongguo' => $shenhetongguo, 'shenhejujue' => $shenhejujue, 'zuofei' => $zuofei]);
    }

    //合同
    public function contract()
    {
        $where = function ($query) {
            $query->where('create_staff_id|owner_staff_id', 'in', Staff::getMyStaffIds())
                ->whereOr('', 'exp', "FIND_IN_SET({$this->auth->id},show_staff_id)");
        };
        $daishenhe = Contract::where([ 'check_status' => ['in', [0, 1]]])->where($where)->count();
        $shenhetongguo = Contract::where([ 'check_status' => 2])->where($where)->count();
        $shenhejujue = Contract::where([ 'check_status' => 3])->where($where)->count();
        $zuofei = Contract::where([ 'check_status' => 4])->where($where)->count();
        $zongzhi = Contract::where([ 'check_status' => 9])->where($where)->count();

        $this->success('请求成功', ['daishenhe' => $daishenhe, 'shenhetongguo' => $shenhetongguo, 'shenhejujue' => $shenhejujue, 'zuofei' => $zuofei, 'zongzhi' => $zongzhi]);
    }

    //费用
    public function consume()
    {
        $where=[];
        $where['staff_id']=$this->auth->id;
        $daishenhe = Consume::where([ 'check_status' => ['in', [0, 1]]])
            ->where($where)->count();
        $shenhetongguo = Consume::where([ 'check_status' => 2])
            ->where($where)->count();
        $shenhejujue = Consume::where([ 'check_status' => 3])
            ->where($where)->count();
        $zuofei = Consume::where([ 'check_status' => 4])
            ->where($where)->count();

        $this->success('请求成功', ['daishenhe' => $daishenhe, 'shenhetongguo' => $shenhetongguo, 'shenhejujue' => $shenhejujue, 'zuofei' => $zuofei]);
    }




    //备件
    public function parts()
    {
        $whereFlow = [];
        $whereFlow[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',flow_staff_id)')];
        $ruku = PartsStockReload::where(['type' => 1, 'check_status' => ['in', [0, 1]]])->where($whereFlow)->count();
        $chuku = PartsStockReload::where(['type' => 2, 'check_status' => ['in', [0, 1]]])->where($whereFlow)->count();
        $quejian = Parts::where(['status' => '上架'])->where('stock <= warning_stock')->count();
        $all = Parts::where(['status' => '上架'])->count();
        $this->success('请求成功', ['ruku' => $ruku, 'chuku' => $chuku, 'quejian' => $quejian, 'all' => $all]);
    }

    //审批
    public function examine()
    {
        $wofaqi = Approval::where([ 'check_status' => ['in', [0, 1]], 'create_staff_id' => $this->auth->id])->count();
        $whereFlow = [];
        $whereFlow[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',flow_staff_id)')];
        $whereFlow[] = ['exp', Db::raw('!FIND_IN_SET(' . $this->auth->id . ',check_staff_ids)')];
        $daishenhe = Approval::where([
             'check_status' => ['in', [0, 1]]
        ])->where($whereFlow)->count();

        $this->success('请求成功', ['wofaqi' => $wofaqi, 'daishenhe' => $daishenhe]);
    }

    //排行
    public function ranking()
    {
        //1 获客 2拜访 3业绩 4回款 5工单
        $ranking = input('ranking');
        $times = input('times');//2021-01,2021-07
        if (empty($times)) {
            $this->error('筛选时间不能为空');
        }
        $times = setTimes($times, 'time');
        $startTime = $times[0];
        $endTime = $times[1];
        $where = [];
        if ($ranking == 1) {//获客
            $rankingList = Customers::where(['createtime' => ['between', [$startTime, $endTime]]])->where('staff_member_id', '>', 0)->where($where)
                ->with(['staff'])
                ->field('count(*) as number,staff_member_id')->order('number desc')->group('staff_member_id')->select();
            $rankingList = collection($rankingList)->toArray();
            // $rankingList = array_slice($rankingList, 0, 10);
            $adminList = [];
            if ($rankingList) {
                $admin_ids = array_column(array_column($rankingList, 'staff'), 'admin_id');
                $adminList = Admin::where(['id' => ['in', $admin_ids]])->column('id,nickname as name,avatar as img', 'id');
            }
            foreach ($rankingList as $k => &$v) {
                $v['ranking'] = $k + 1;
                $v['staff'] = $adminList[$v['staff']['admin_id']] ?? $v['staff'];
                $v['staff']['img'] = cdnurl($v['staff']['img'], true);
                $v['unit'] = '个';
            }
        } elseif ($ranking == 2) {//拜访

            // $rankingList = Event::where(['type' => 3, 'status' => 2, 'actual_end_time' => ['between', [$startTime, $endTime]]])->where($where)
                // ->with(['staff'])->field('count(*) as number,staff_id')->order('number desc')->group('staff_id')->select();
            $rankingList = StaffSignIn::where([ 'createtime' => ['between', [$startTime, $endTime]]])->where($where)
                ->with(['staff'])->field('count(*) as number,staff_id')->order('number desc')->group('staff_id')->select();
            $rankingList = collection($rankingList)->toArray();
            // $rankingList = array_slice($rankingList, 0, 10);
            if ($rankingList) {
                $admin_ids = array_column(array_column($rankingList, 'staff'), 'admin_id');
                $adminList = Admin::where(['id' => ['in', $admin_ids]])->column('id,nickname as name,avatar as img', 'id');
            }
            foreach ($rankingList as $k => &$v) {
                $v['ranking'] = $k + 1;
                $v['staff'] = $adminList[$v['staff']['admin_id']] ?? $v['staff'];
                $v['staff']['img'] = cdnurl($v['staff']['img'], true);
                $v['unit'] = '次';
            }
        } elseif ($ranking == 3) {//业绩
            $rankingList = GoodsSales::where(['examine_status' => 1, 'purchase_time' => ['between', [$startTime, $endTime]]])->where($where)->with(['staff'])->field('sum(real_money+back_money) as number,sale_user')->order('number desc')->group('sale_user')->select();
            $rankingList = collection($rankingList)->toArray();
            // $rankingList = array_slice($rankingList, 0, 10);
            if ($rankingList) {
                $admin_ids = array_column(array_column($rankingList, 'staff'), 'admin_id');
                $adminList = Admin::where(['id' => ['in', $admin_ids]])->column('id,nickname as name,avatar as img', 'id');
            }
            foreach ($rankingList as $k => &$v) {
                $v['ranking'] = $k + 1;
                $v['number'] = round($v['number'], 2);
                $v['staff'] = $adminList[$v['staff']['admin_id']] ?? $v['staff'];
                $v['staff']['img'] = cdnurl($v['staff']['img'], true);
                $v['unit'] = '元';
            }
        } elseif ($ranking == 4) {//回款

            $rankingList = Collection::where(['examine_status' => 1, 'purchase_time' => ['between', [$startTime, $endTime]]])->where($where)
                ->with(['staff'])->field('sum(money) as number,staff_member_id')->order('number desc')->group('staff_member_id')->select();

            $rankingList = collection($rankingList)->toArray();
            // $rankingList = array_slice($rankingList, 0, 10);
            if ($rankingList) {
                $admin_ids = array_column(array_column($rankingList, 'staff'), 'admin_id');
                $adminList = Admin::where(['id' => ['in', $admin_ids]])->column('id,nickname as name,avatar as img', 'id');
            }
            foreach ($rankingList as $k => &$v) {
                $v['ranking'] = $k + 1;
                $v['number'] = round($v['number'], 2);
                $v['staff'] = $adminList[$v['staff']['admin_id']] ?? $v['staff'];
                $v['staff']['img'] = cdnurl($v['staff']['img'], true);
                $v['unit'] = '元';
            }
        }
        foreach ($rankingList as $kes => $ves) {
            if(empty($ves['staff'])){
                unset($rankingList[$kes]);
            }
        }
        $this->success('请求成功', array_values($rankingList));
    }

    //搜索
    public function search()
    {
        $keywords = input('keywords');
        $type = input('type');
        if (empty($keywords)) {
            $this->error('筛选字段不能为空');
        }
        //客户
        $customer = Customers::where([
            'customer_name' => ['like', "%$keywords%"],
            'staff_member_id' => ['in', Staff::getMyStaffIds()],
        ])->with([
            'ownerStaff',
            'contacts'
        ])->field('id,name,next_time,owner_staff_id,level,follow')->select();
        //联系人
        $contacts = Contacts::where([
            'name' => ['like', "%$keywords%"],
            'owner_staff_id' => ['in', Staff::getMyStaffIds()],
        ])->with(['customer'])->field('id,name,mobile,customer_id')->select();
        //线索
        // $leads = Leads::where([
        //     'name' => ['like', "%$keywords%"],
        //     'owner_staff_id' => ['in', Staff::getMyStaffIds()],
        // ])->with(['ownerStaff'])->field('id,owner_staff_id,name,follow,mobile')->select();

        $this->success('请求成功', [
            'customer' => $customer,
            'contacts' => $contacts,
            'leads' => []//$leads
        ]);
    }

    //反馈
    public function feedback()
    {
        $content = input('content', '');
        $file = input('file', '');
        if (empty($content)) {
            $this->error('请输入反馈内容！');
        }
        $model = new Feedback();
        $model->save([
            'staff_id' => $this->auth->id,
            
            'content' => $content,
            'file_ids' => $file
        ]);
        $this->success('反馈成功');
    }

    //服务协议
    public function serviceContent()
    {
        $this->success('请求成功', [
            'content' => "<h1>用户服务协议</h1>",
            'name' => '青动',
            'logo' => '/assets/img/logo.png'
        ]);
    }


    //待办事项
    public function agent() {
        $where['create_staff_id'] = $this->auth->id;
        $where['next_time'] = array(array('egt',date('Y-m-d 00:00:00')),array('lt',date('Y-m-d 23:59:59')));
        $where['follow_type'] = ['neq', '其它'];
        $where['status'] = 0;
        // 待跟进客户
        $where1['relation_type'] = 1;
        $customerlist = Record::where($where)->where($where1)->column('id');
        $customerlist1 = 0;
        if($customerlist){
            $whereExit['id'] = array('in',$customerlist);
            $whereExit['next_time'] = array('gt',date('Y-m-d 23:59:59'));
            $customerlist1 = Record::where($whereExit)->count();
        }
        $customer = count($customerlist) - $customerlist1;

        //待跟进合同
        $where2['relation_type'] = 3;
        $contractlist = Record::where($where)->where($where2)->column('id');
        $contractlist1 = 0;
        if($contractlist){
            $whereExitC['id'] = array('in',$contractlist);
            $whereExitC['next_time'] = array('gt',date('Y-m-d 23:59:59'));
            $contractlist1 = Record::where($whereExitC)->count();
        }
        $contract = count($contractlist)-$contractlist1;
        //待跟进线索
        $where3['relation_type'] = 4;
        $leadlist = Record::where($where)->where($where3)->column('id');
        $leadlist1 = 0;
        if($leadlist){
            $whereExitL['id'] = array('in',$leadlist);
            $whereExitL['next_time'] = array('gt',date('Y-m-d 23:59:59'));
            $leadlist1 = Record::where($whereExitL)->count();
        }
        $lead = count($leadlist)-$leadlist1;
        //待跟进联系人
        $where4['relation_type'] = 2;
        $contactslist = Record::where($where)->where($where4)->column('id');
        $contactslist1 = 0;
        if($contactslist1){
            $whereExitCs['id'] = array('in',$contactslist);
            $whereExitCs['next_time'] = array('gt',date('Y-m-d 23:59:59'));
            $contactslist1 = Record::where($whereExitCs)->count();
        }
        $contacts = count($contactslist)-$contactslist1;
        //待跟进商机
        $where5['relation_type'] = 5;
        $businesslist = Record::where($where)->where($where5)->column('id');
        $businesslist1 = 0;
        if($businesslist1){
            $whereExitB['id'] = array('in',$businesslist);
            $whereExitB['next_time'] = array('gt',date('Y-m-d 23:59:59'));
            $businesslist1 = Record::where($whereExitB)->count();
        }
        $business = count($businesslist)-$businesslist1;

        //待审核合同
        $examine = ExamineRecord::where([
            'relation_type'  => ExamineRecord::CONTRACT_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //待审核回款
        $receivables = ExamineRecord::where([
            'relation_type'  => ExamineRecord::RECEIVABLES_TYPE,
            'status'         => 0,
            'check_staff_id' => $this->auth->id
        ])->count();
        //待回款提醒
        $receivablesPlan = ReceivablesPlan::where([
            'remind_date'    => ['elt', date('Y-m-d')],
            'status'         => 0,
            'owner_staff_id' => $this->auth->id
        ])->count();
        //待处理日程
        $eventOne = Event::where([
            'type'       => 1,
            'status'     => ['in', [0, 1]],
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'staff_id|owner_staff_id'   => $this->auth->id,
        ])->count();
        $this->success('请求成功', [
            'customer'         => $customer,
            'business'         => $business,
            'contract'         => $contract,
            'lead'             => $lead,
            'contacts'         => $contacts,
            'event_one'        => $eventOne,
            'examine'          => $examine,
            'receivables'      => $receivables,
            'receivables_plan' => $receivablesPlan
        ]);
    }
    //待处理日程
    public function event_one() {
        //待办日程
        $eventWhere = [
            'status' => ['in', [0, 1]],
            'start_time' => ['lt', date('Y-m-d', strtotime('+1 day'))],
            'end_time' => ['gt', date('Y-m-d H:i:s')],
            'staff_id' => $this->auth->id,
        ];
        $event = Event::where($eventWhere)->with([
            'staff',
            'customer',
        ])->order('id desc')->select();
        $event=collection($event)->toArray();
        foreach ($event as $k => $v) {
            $v['level'] = Event::getLevel($v['level']);
            $v['status'] = Event::getStatus($v['status']);

            $event[$k] = $v;
        }
        $this->success('请求成功', $event);
    }

    //待回款提醒
    public function examine_receivables_plan() {
        //待回款提醒
        $receivablesPlan = ReceivablesPlan::where([
            'remind_date'    => ['elt', date('Y-m-d')],
            'status'         => 0,
            'owner_staff_id' => $this->auth->id,
        ])->order('id desc')->with(['contract', 'customer'])->select();

        $this->success('请求成功', $receivablesPlan);
    }

}
